package com.zito.health.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zito.health.common.annotations.ResponseResult;
import com.zito.health.common.result.PageResult;
import com.zito.health.common.result.VerifyResult;
import com.zito.health.dto.LaboratoryDto;
import com.zito.health.dto.LaboratoryLinkmanDto;
import com.zito.health.dto.LaboratoryPrint1Dto;
import com.zito.health.dto.LaboratoryPrint2Dto;
import com.zito.health.entity.Laboratory;
import com.zito.health.entity.LaboratoryLinkman;
import com.zito.health.entity.LaboratoryVo;
import com.zito.health.entity.User;
import com.zito.health.service.LaboratoryLinkmanService;
import com.zito.health.service.LaboratoryService;
import com.zito.health.util.CacheUtil;
import com.zito.health.vo.LabCoordinateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @description: 实验室基础信息
 * @author: gxt
 * @time: 2019/11/8 15:31
 */
@Slf4j
@ResponseResult
@RestController
@RequestMapping("/laboratory")
public class LaboratoryController {

    @Autowired
    private LaboratoryService laboratoryService;
    @Autowired
    private LaboratoryLinkmanService laboratoryLinkmanService;

    /**
     * 实验室备案申报
     * @param laboratory
     * @return
     */
    @PostMapping
    public VerifyResult save(Laboratory laboratory){
        VerifyResult verifyResult = new VerifyResult();
//        if(laboratory.getName()==null){
//            verifyResult.setResult(false);
//            verifyResult.setMsg("实验室名称或申报时间为空");
//            return verifyResult;
//        }
        User user = CacheUtil.getCacheUser().getUser();
        laboratory.setUserid(user.getUserid());
        laboratory.setUnitId(user.getUnitId());
        laboratory.setStates(8);
        Date date=new Date();
        laboratory.setEstablishTime(date);
        laboratory.setDeclareTime(date);//实验室申报时间
        laboratory.setLife(5);//这个地方得改
        laboratoryService.save(laboratory);
        verifyResult.setMsg(String.valueOf(laboratory.getId()));
        return verifyResult;
    }

    /**
     * 实验室基础信息的保存
     * @param dto
     * @return
     */
    @PostMapping("/saveBase")
    public VerifyResult saveBase(LaboratoryLinkmanDto dto){
        VerifyResult verifyResult = new VerifyResult();
        Laboratory laboratory=new Laboratory();
        LaboratoryLinkman laboratoryLinkman= new LaboratoryLinkman();
        BeanUtils.copyProperties(dto,laboratory);
        BeanUtils.copyProperties(dto,laboratoryLinkman);

        String[] coordinate=dto.getCoordinate().split(",");
        laboratory.setLng(coordinate[0]);
        laboratory.setLat(coordinate[1]);
        laboratoryService.update(laboratory);

        laboratoryLinkman.setLaboratoryId(dto.getId());
        laboratoryLinkman.setName(dto.getLinkmanName());
        LaboratoryLinkman linkman=new LaboratoryLinkman();
        linkman.setLaboratoryId(dto.getId());

        linkman= laboratoryLinkmanService.queryOne(linkman);
        if(linkman==null){
            laboratoryLinkman.setId(null);
            laboratoryLinkmanService.save(laboratoryLinkman);
        }else{

            laboratoryLinkman.setId(linkman.getId());
            laboratoryLinkmanService.update(laboratoryLinkman);
        }
        return verifyResult;
    }

    /**
     * 实验室基础信息
     * @param laboratory
     * @return
     */
    @PutMapping
    public VerifyResult update(Laboratory laboratory){
        VerifyResult verifyResult = new VerifyResult();
        laboratoryService.update(laboratory);
        return verifyResult;
    }

    /**
     * 实验室提交
     * @param laboratory
     * @return
     */
    @PutMapping("/sysSubmit")
    public VerifyResult sysSubmit(Laboratory laboratory){
        VerifyResult verifyResult = new VerifyResult();
        String res = laboratoryService.canSubmit(laboratory);
        if(!"ok".equals(res)){
            verifyResult.setResult(false);
            verifyResult.setMsg(res);
            return verifyResult;
        }
        laboratory.setDeclareTime(new Date());
        laboratoryService.update(laboratory);
        return verifyResult;
    }
    /**
     * 实验室提交用（暂时没用）
     * @param laboratory
     * @return
     */
    @PutMapping("/submit")
    public VerifyResult Submit(Laboratory laboratory, HttpServletRequest request){
        VerifyResult verifyResult = new VerifyResult();

        Laboratory leLaboratory = laboratoryService.queryLaboratoryById(laboratory.getId());
        if (leLaboratory != null) {
            leLaboratory.setStates(1);
//
//            String token = DigestUtils.md5Hex("370100wjw" + "3701000103608" +
//                    "wjw370100");
//
//            String j ="http://221.214.14.40:81/unitCode/web/inspur/uniteCode/getUniteCode?appCode=370100wjw&itemId=" +
//                    "3701000103608&regionCode=370100&powerType=01&token="+token;
//            String code = this.getURLContent(j);
//            JSONObject jasonObject = JSONObject.parseObject(code);
//
//            Map map = (Map)jasonObject;
//            leLaboratory.setProjid(map.get("unitecode").toString());
//            leLaboratory.setProjpwd(map.get("password").toString());
            laboratoryService.update(leLaboratory);

//            SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
//            //对接传数据
//            User uu = userService.queryUserById(leLaboratory.getUserid());
//            EaJcStepBasicinfo b = new EaJcStepBasicinfo();
//
//            b.setOrgbusno(leLaboratory.getId().toString());
//            b.setProjid(map.get("unitecode").toString());
//            b.setProjpwd(map.get("password").toString());
//            b.setValidityFlag((short)1);
//            b.setDataver((short)1);
//            b.setItemno("3701001003606");
//            //新建、改建或者扩建一级、二级生物安全实验室备案
//            b.setItemname("新建、改建或者扩建一级、二级生物安全实验室备案");
//
//            b.setProjectname("关于济南市卫生健康委员会申报"+leLaboratory.getName()+"的业务");
//            b.setApplicant(uu.getFullname());
//            b.setApplicanttype("1");
//            b.setApplicantcardtype("10");
//            if(uu.getSid()!=null && !"".equals(uu.getSid())){
//                b.setApplicantcardcode(uu.getSid());
//            }else{
//                b.setApplicantcardcode("1");
//            }
//
//
//            b.setApplicantmobile(uu.getTelephone());
//            b.setAcceptlist("申报首页,实验室基本信息,实验室人员,实验室负责人,基础设施,生物安全及防护设备,制度,实验活动基本情况一,实验活动基本情况二,上传附件");
//            b.setContactman(uu.getFullname());
//            b.setUnifiedcode("-");
//            b.setBusinesslicense("-");
//            b.setTaxcode("-");
//            b.setAcceptdeptid("370100036");
//            b.setAcceptdeptname("济南市卫生健康委员会");
//            b.setApprovaltype("4");
//            b.setPromisetimelimit(1);
//            b.setPromisetimeunit("5");
//            b.setOccurtime(new Date());
//            b.setMaketime(new Date());
//            b.setSignstate("1");
//            b.setStdver(1);
//
//
//
//            String params = "orgbusno="+b.getOrgbusno()+"&projid="+b.getProjid()+"&projpwd="+b.getProjpwd()	+"&validityFlag="+b.getValidityFlag()
//                    +"&dataver="+b.getDataver()+"&itemno="+b.getItemno()+"&itemname="+b.getItemname()+"&projectname="+b.getProjectname()
//                    +"&applicant="+b.getApplicant()+"&applicanttype="+b.getApplicanttype()+"&applicantcardtype="+b.getApplicantcardtype()+"&applicantcardcode="+b.getApplicantcardcode()
//                    +"&applicantmobile="+b.getApplicantmobile()+"&acceptlist="+b.getAcceptlist()+"&contactman="+b.getContactman()
//                    +"&unifiedcode="+b.getUnifiedcode()+"&businesslicense="+b.getBusinesslicense()+"&taxcode="+b.getTaxcode()
//                    +"&acceptdeptid="+b.getAcceptdeptid()+"&acceptdeptname="+b.getAcceptdeptname()+"&approvaltype="+b.getApprovaltype()
//                    +"&promisetimelimit="+b.getPromisetimelimit()+"&promisetimeunit="+b.getPromisetimeunit()+"&occurtime="+b.getOccurtime()
//                    +"&maketime="+b.getMaketime()+"&signstate="+b.getSignstate()+"&stdver="+b.getStdver();
//
//
//            PreapasinfoController.sendPost("http://127.0.0.1:9000/login/insertPreApasinfo.do", params);
//
//
//
//            EaJcStepProc c = new EaJcStepProc();
//            c.setOrgbusno(leLaboratory.getId().toString());
//            c.setProjid(leLaboratory.getProjid());
//            c.setValidityFlag((short)1);
//            c.setDataver((short)1);
//            c.setStdver(1);
//            c.setNodename("审核");
//            c.setNodetype("4");
//
//            if (leLaboratory.getAreaId()!=null) {
//                Map<String,Object> proparam = new HashMap<String,Object>();
//                proparam.put("areaId", leLaboratory.getAreaId());
//                List<User> ulist = userService.selectAll(proparam);
//                if (ulist.size()>0) {
//                    c.setNodeprocer(ulist.get(ulist.size()-1).getUserid().toString());
//                    c.setNodeprocername(ulist.get(ulist.size()-1).getFullname());
//                }else{
//                    c.setNodeprocer("8");
//                    c.setNodeprocername("市卫计委");
//                }
//                c.setProcunit(leLaboratory.getAreaId().toString());
//                c.setProcunitname(areaService.queryById(leLaboratory.getAreaId()).getAreaName()+"卫计局");
//            }else{
//                c.setNodeprocer("8");
//                c.setNodeprocername("市卫计委");
//                c.setProcunit("3708");
//                c.setProcunitname("济南市卫计局");
//            }
//
//            c.setNodestate("01");
//            c.setNodestarttime(leLaboratory.getDeclareTime());
//            c.setNodeendtime(leLaboratory.getDeclareTime());
//            c.setNoderesult("4");
//            c.setOccurtime(leLaboratory.getDeclareTime());
//            c.setMaketime(new Date());
//            c.setSignstate("1");
//            String params1 = "orgbusno="+c.getOrgbusno()+"&projid="+c.getProjid()+"&validityFlag="+c.getValidityFlag()
//                    +"&dataver="+c.getDataver()+"&stdver="+c.getStdver()+"&nodename="+c.getNodename()
//                    +"&nodetype="+c.getNodetype()+"&nodeprocer="+c.getNodeprocer()+"&nodeprocername="+c.getNodeprocername()+"&procunit="+c.getProcunit()+"&procunitname="+c.getProcunitname()
//                    +"&nodestate="+c.getNodestate()+"&nodestarttime="+c.getNodestarttime()+"&nodeendtime="+c.getNodeendtime()
//                    +"&noderesult="+c.getNoderesult()+"&occurtime="+c.getOccurtime()+"&maketime="+c.getMaketime()
//                    +"&signstate="+c.getSignstate();
//
//            PreapasinfoController.sendPost("http://127.0.0.1:9000/login/insertEaJcStepProc.do", params1);

        } else {
            verifyResult.setResult(Boolean.FALSE);
        }

        return verifyResult;
    }

    @GetMapping
    public PageResult list(LaboratoryDto laboratoryDto, @RequestParam(defaultValue = "0") Integer pageNo, @RequestParam(defaultValue = "10")Integer pageSize){

        User user = CacheUtil.getCacheUser().getUser();
        if(user.getRoleId()==1){//1.admin
            laboratoryDto.setStatesStr("1,2,3,5");
        }else if(user.getRoleId()==2) {//2市局
            laboratoryDto.setStatesStr("1,2,3,5");
        }else if(user.getRoleId()==3){//县局
            laboratoryDto.setAreaId(user.getAreaId());
            laboratoryDto.setStatesStr("1,2,3,5");
        }else if(user.getRoleId()==9){//实验室单位管理员
            laboratoryDto.setUnitId(user.getUnitId());//单位id
            laboratoryDto.setStatesStr("8,1,2,3,5");//8是未提交
        }
        if(laboratoryDto.getStates() == 4){//实验室变更列表-变更按钮用或巡检
            laboratoryDto.setStatesStr("4");
        }
        PageHelper.startPage(pageNo,pageSize);
        List<LaboratoryDto> list = laboratoryService.queryLaboratory(laboratoryDto);
        PageInfo<LaboratoryDto> pageInfo = new PageInfo(list);
        PageResult<LaboratoryDto> result = new PageResult();
        result.setRows(pageInfo.getList());
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    @GetMapping("/list4Archives")
    public PageResult list4Archives(LaboratoryDto laboratoryDto, @RequestParam(defaultValue = "0") Integer pageNo, @RequestParam(defaultValue = "10")Integer pageSize){

        User user = CacheUtil.getCacheUser().getUser();
        laboratoryDto.setStatesStr("4,6,7");
        PageHelper.startPage(pageNo,pageSize);
        List<LaboratoryDto> list = laboratoryService.list4Archives(laboratoryDto);
        PageInfo<LaboratoryDto> pageInfo = new PageInfo(list);
        PageResult<LaboratoryDto> result = new PageResult();
        result.setRows(pageInfo.getList());
        result.setTotal(pageInfo.getTotal());
        return result;
    }

    @GetMapping("/{id}")
    public Laboratory queryById(@PathVariable Integer id){
        Laboratory laboratory = laboratoryService.queryById(id);
        return laboratory;
    }

    @GetMapping("/audit/{id}")
    public LaboratoryVo getById(@PathVariable Integer id){
        LaboratoryVo laboratoryVo = laboratoryService.getById(id);
        return laboratoryVo;
    }

    @GetMapping("/print1/{id}")
    public LaboratoryPrint1Dto print1(@PathVariable Integer id){
        LaboratoryPrint1Dto laboratoryPrint1Dto = new LaboratoryPrint1Dto();
        if (id != null ) {
            laboratoryPrint1Dto = laboratoryService.print1(id);
        }
        return laboratoryPrint1Dto;
    }
    @GetMapping("/print2/{id}")
    public LaboratoryPrint2Dto print2(@PathVariable Integer id){
        LaboratoryPrint2Dto laboratoryPrint2Dto = new LaboratoryPrint2Dto();
        if (id != null ) {
            laboratoryPrint2Dto = laboratoryService.print2(id);
        }
        return laboratoryPrint2Dto;
    }

    /**
     * 实验室删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public VerifyResult delete(@PathVariable Integer id){
        VerifyResult verifyResult = new VerifyResult();
        laboratoryService.deleteById(id);
        return verifyResult;
    }

    @GetMapping("/getCoordinates")
    public List<LabCoordinateVo> getCoordinates(String labName){
        LabCoordinateVo vo = new LabCoordinateVo();
        List<LabCoordinateVo> voList=laboratoryService.getCoordinates(labName);
        return voList;
    }
    @GetMapping("/getLabNum")
    public Integer getLabNum(){
        return laboratoryService.getLabNum();
    }

}
